package com.usky.pss.refundticket.work;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.springframework.stereotype.Service;

import com.usky.pss.ibe.entity.ticket.TicketSegment;
import com.usky.pss.ibe.result.RetrieveTicketResultInfo;
import com.usky.pss.ibe.service.IBEService;
import com.usky.pss.ibe.service.support.IBEServiceImpl;

/**
 * Created by Jeremy on 2016/11/11.
 */
@Service
public class TicketStatusWorker implements Runnable{

    private ConcurrentLinkedQueue<TicketStatusTask> workQueue;

    private ConcurrentHashMap<String,TicketStatusTask> workResult;

    public ConcurrentLinkedQueue<TicketStatusTask> getWorkQueue() {
        return workQueue;
    }

    public void setWorkQueue(ConcurrentLinkedQueue<TicketStatusTask> workQueue) {
        this.workQueue = workQueue;
    }

    public ConcurrentHashMap<String, TicketStatusTask> getWorkResult() {
        return workResult;
    }

    public void setWorkResult(ConcurrentHashMap<String, TicketStatusTask> workResult) {
        this.workResult = workResult;
    }


//    @Autowired
    private IBEService ibeService = new IBEServiceImpl();
    @Override
    public void run() {
        while (true){
            TicketStatusTask task = this.getWorkQueue().poll();
            if (task == null) break;
            task = this.handle(task);
            this.workResult.put(task.getTicketNo(),task);
        }
    }

    public TicketStatusTask handle(TicketStatusTask task){
        //todo
        System.out.println(">>>>> ticket NO("+task.getTicketNo()+")'s thread is handling! ");
        String ticketNo = task.getTicketNo();
        List<String> list = new ArrayList<String>(Arrays.asList(ticketNo));
        try {
            List<RetrieveTicketResultInfo> checkTicketResult = ibeService.retrieveTicket(list);
            for (RetrieveTicketResultInfo checkTicketResultInfo : checkTicketResult){
                List<TicketSegment> segmentStatusList = checkTicketResultInfo.getSegmentStatusList();
                task.setTaskResult(segmentStatusList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return task;
    }

}
